package com.health.mapp.impl;

import io.rong.models.TokenReslut;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;


import com.health.commons.MD5Password;
import com.health.commons.PropertiesService;
import com.health.db.dto.StuffDetailDto;
import com.health.db.model.UserLIST;
import com.health.db.model.UserLISTTemp;
import com.health.db.model.UserLoginJournal;
import com.health.db.service.msg.IUserLoginJournalService;
import com.health.db.service.sm.IRongService;
import com.health.db.service.user.IStuffListService;
import com.health.db.service.user.IUserLISTService;
import com.health.mapp.bean.Header;
import com.health.mapp.bean.LoginReq;
import com.health.mapp.bean.LoginResp;
import com.health.mapp.utils.Constant;
import com.health.mapp.utils.DateUtils;
import com.health.mapp.utils.Response;
import com.health.mapp.utils.ResultCode;

/**
 * 登录
 * 
 * IsExportFlag属性 1为旧线下用户，不提供登录。用户注册，更新原表中的注册信息 2为旧线上用户，用户登录，不校验密码。
 * 
 * @author yuchong
 * 
 */
public class LoginImpl implements ActionInterface {

	private static Logger logger = Logger.getLogger(LoginImpl.class);
	private IUserLISTService userLISTService;
	private IStuffListService stuffListService;
	private IRongService rongService;
	private IUserLoginJournalService userLoginJournalService;

	boolean flag = false;

	@Override
	public Response execute(Header header, Object reqBean) {

		LoginReq req = (LoginReq) reqBean;
		LoginResp _resp = new LoginResp();

		String userNo = req.getUserPhone();
		String passWord = req.getPassword();
		UserLIST user = null;
		user = userLISTService.selectByUserNo(userNo);
		// 更新登录信息
		UserLIST userLISTForUpdate = new UserLIST();

		if (null != user) {
			// check the userid
			UserLISTTemp userLIST = new UserLISTTemp();

			userLIST.setUserId(String.valueOf(user.getUserid()));
			userLIST.setUserName(user.getUserName());
			userLIST.setUserPhone(user.getUserNo());
			userLIST.setRegTime(user.getRegisterDate());
			userLIST.setIcon(user.getIconUrl());
			userLIST.setToken(user.getApptoken());

			if (null != user.getIsExportFlag()) {
				userLIST.setIsExportFlag(user.getIsExportFlag());
			}

			//查询是否为vip
			if (null!=user.getVipLevel()&&null!=user.getVipEndDate()) {
				
				if (user.getVipEndDate().compareTo(DateUtils.now())>0) {
					userLIST.setVipLevel(user.getVipLevel().toString());
				}
			}
			userLIST.setUserTypeId(user.getTypeid());

			Short isExportFlag = user.getIsExportFlag();
			logger.debug("user.getPassword():" + user.getPassword());
			// 01000000 旧版本密码已开头
			if (null != isExportFlag && isExportFlag.intValue() == 2){
				
			}else if (null == user.getPassword() || "".equals(user.getPassword())
					|| user.getPassword().startsWith("01000000")) {

				UserLIST updateUser = new UserLIST();
				updateUser.setPassword(MD5Password
						.getEncodedPassword_Hex(passWord));
				updateUser.setUserid(user.getUserid());
				updateUser.setPasswordCreateDate(DateUtils.now());
				updateUser.setUserNo(userNo);

				userLISTService.updatePassword(updateUser);

			} else {

				// 密码校验
				if (!MD5Password.getEncodedPassword_Hex(passWord).equals(
						user.getPassword())) {
					_resp.setErrorCode(ResultCode.LOGIN_FAIL_PASSWORD_IS_ERROR);
					_resp.setErrorMsg(ResultCode.LOGIN_FAIL_PASSWORD_IS_ERROR_NOTE);
					return _resp;
				}
			}

			String iconUrl = userLIST.getIcon();
			// 如果是医生
			if (userLIST.getUserTypeId().intValue() == Constant.CONSTANTS_USER_ROLE_ID_3.intValue()) {
				// docImage/kefu.png
				StuffDetailDto stuffDetailDto = stuffListService
						.selectByStuffId(user.getUserid());

				if (null != stuffDetailDto) {
					String docIconUrl = stuffDetailDto.getIconUrl();
					if (StringUtils.isNotBlank(docIconUrl)) {
						iconUrl = docIconUrl;
					} else {
						iconUrl = PropertiesService.getString(
								"iconUrl.docDefaultUrl").trim();
					}
				} else {
					_resp.setErrorCode(ResultCode.LOGIN_FAIL_MEMBER_IS_NOT_EXISTS);
					_resp.setErrorMsg(ResultCode.LOGIN_FAIL_MEMBER_IS_NOT_EXISTS_NOTE);
					return _resp;
				}
			} else {
				// 设置默认头像
				if (StringUtils.isBlank(iconUrl)) {
					iconUrl = PropertiesService.getString(
							"iconUrl.userDefaultUrl").trim();
				}
			}

			if (StringUtils.isBlank(userLIST.getToken())) {
				/**
				 * token为空的话重新从融云获取Token
				 * */
				TokenReslut tokenReslut = rongService.getUserToken(String
						.valueOf(userLIST.getUserId()), userLIST.getUserName(),
						iconUrl);
				if (null != tokenReslut && tokenReslut.getCode().intValue() == 200) {
					// 更新user的AppToken
					userLISTForUpdate.setApptoken(tokenReslut.getToken());
					_resp.setErrorCode(ResultCode.OPERATION_SUCCESS);
					_resp.setErrorMsg("Success");
					_resp.setUserId(String.valueOf(userLIST.getUserId()));
					_resp.setToken(tokenReslut.getToken());
					_resp.setUser(userLIST);

				} else {
					_resp.setErrorCode(-1);
					_resp.setErrorMsg("获取Token失败");
				}
			} else {
				_resp.setErrorCode(ResultCode.OPERATION_SUCCESS);
				_resp.setErrorMsg("Success");
				_resp.setUserId(String.valueOf(userLIST.getUserId()));
				_resp.setToken(userLIST.getToken());
				_resp.setUser(userLIST);
			}

			userLISTForUpdate.setUserid(Long.valueOf(userLIST.getUserId()));
			userLISTForUpdate.setLoginDatetime(DateUtils.now());
			userLISTForUpdate.setUserNo(userNo);
			userLISTForUpdate.setMachinedeviceid(header.getUuId());
			userLISTService.updateLoginInfo(userLISTForUpdate);

			UserLoginJournal loginJournal = new UserLoginJournal();

			loginJournal.setUserid(Long.valueOf(userLIST.getUserId()));
			loginJournal.setMachinedeviceid(req.getUuid());
			loginJournal.setLoginDatetime(DateUtils.now());

			if (req.getOs() == null) {
				loginJournal.setLoginFlag((short) 0);
			} else {
				loginJournal.setLoginFlag((short) 1);
			}

			if (null != req.getOs()) {
				loginJournal.setLoginFlag(Short.valueOf(req.getOs()));
			} else {
				loginJournal.setLoginFlag((short) 0);
			}
			userLoginJournalService.insert(loginJournal);

		} else {
			_resp.setErrorCode(ResultCode.LOGIN_FAIL_MEMBER_IS_NOT_EXISTS);
			_resp.setErrorMsg(ResultCode.LOGIN_FAIL_MEMBER_IS_NOT_EXISTS_NOTE);
		}

		return _resp;

	}

	public IUserLISTService getUserLISTService() {
		return userLISTService;
	}

	public void setUserLISTService(IUserLISTService userLISTService) {
		this.userLISTService = userLISTService;
	}

	public static Logger getLogger() {
		return logger;
	}

	public static void setLogger(Logger logger) {
		LoginImpl.logger = logger;
	}

	public IStuffListService getStuffListService() {
		return stuffListService;
	}

	public void setStuffListService(IStuffListService stuffListService) {
		this.stuffListService = stuffListService;
	}

	public boolean isFlag() {
		return flag;
	}

	public void setFlag(boolean flag) {
		this.flag = flag;
	}

	public IRongService getRongService() {
		return rongService;
	}

	public void setRongService(IRongService rongService) {
		this.rongService = rongService;
	}

	/**
	 * @return the userLoginJournalService
	 */
	public IUserLoginJournalService getUserLoginJournalService() {
		return userLoginJournalService;
	}

	/**
	 * @param userLoginJournalService
	 *            the userLoginJournalService to set
	 */
	public void setUserLoginJournalService(
			IUserLoginJournalService userLoginJournalService) {
		this.userLoginJournalService = userLoginJournalService;
	}

}
